package com.rcadmin.busi.templateapi.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.rcadmin.busi.templateapi.contant.BlockLinkType;
import com.rcadmin.busi.templateapi.dto.SpecBlockReq;
import com.rcadmin.busi.templateapi.dto.WebBlockDto;
import com.rcadmin.busi.templateapi.dto.WebTemplateKeyResp;
import com.rcadmin.busi.web.dao.BlockDao;
import com.rcadmin.busi.web.dao.GroupKeyDao;
import com.rcadmin.busi.web.dao.TemplateDao;
import com.rcadmin.busi.web.dao.TemplatePackageDao;
import com.rcadmin.busi.web.ddl.WebBlock;
import com.rcadmin.busi.web.ddl.WebBlockVar;
import com.rcadmin.busi.web.ddl.WebTemplate;
import com.rcadmin.busi.web.ddl.WebTemplateGroupkey;
import com.rcadmin.util.BeanCopy;

/**
 * 网站块配置服务类
 * 
 * @author tansonlam
 * @createDate 2016年3月3日
 * 
 */
@Repository("webBlockService")
public class WebBlockService {
	@Resource
	private TemplatePackageDao templatePackageDao;
	@Resource
	private TemplateDao templateDao;
	@Resource
	private BlockDao blockDao;
	@Resource
	private GroupKeyDao groupKeyDao;
	@Resource
	private WebBlockVarService webBlockVarService;

	/**
	 * 查找商店使用的模板页面配置的分组属性
	 * 
	 * @param userId
	 *            用户ID
	 * @param templatePackageId
	 *            模板包ID
	 * @param templateName
	 *            模板名称
	 * @return
	 */
	public List<WebTemplateKeyResp> listTemplateBlock(Integer userId,
			Integer templatePackageId, String templateName) {
		return listTemplateBlock(userId, templatePackageId, templateName, null);
	}

	/**
	 * 查找商店使用的模板页面配置的分组属性
	 * 
	 * @param userId
	 *            用户ID
	 * @param templatePackageId
	 *            模板包ID
	 * @param templateName
	 *            模板名称
	 * @return
	 */
	public List<WebTemplateKeyResp> listTemplateBlock(Integer userId,
			Integer templatePackageId, String templateName, String urlReqParam) {
		// url指定内容id
		List<SpecBlockReq> specBlockReqList = SpecBlockReq
				.parse2SpecBlockReq(urlReqParam);

		// 查找对应的模板
		WebTemplate webTemplate = templateDao.findByTemplateName(userId,
				templateName, templatePackageId);
		if (webTemplate == null
				|| StringUtils.isEmpty(webTemplate.getGroupKeys()))
			return Collections.emptyList();

		List<String> groupKeys = Lists.newArrayList(webTemplate.getGroupKeys()
				.split(","));
		for (SpecBlockReq specBlockReq : specBlockReqList) {
			groupKeys.add(specBlockReq.getGroupKey());
		}
		// 查询模板使用的分类信息
		List<WebTemplateGroupkey> groupKeyInfos = groupKeyDao.findGroupKeys(
				templatePackageId, groupKeys);

		List<Integer> groupKeyids = Lists.newArrayList();
		for (WebTemplateGroupkey webTemplateGroupkey : groupKeyInfos) {
			if (webTemplateGroupkey != null
					&& !SpecBlockReq.isInSpecBlockReq(specBlockReqList,
							webTemplateGroupkey.getGroupKey()))
				groupKeyids.add(webTemplateGroupkey.getId());
		}
		// 组装指定内容ID
		List<Integer> speckBlockids = Lists.newArrayList();
		for (SpecBlockReq specBlockReq : specBlockReqList) {
			for (Integer blockId : specBlockReq.getBlockIds())
				speckBlockids.add(blockId);
		}

		// 获取模板所有的关联的网页块配置
		List<WebBlock> webBlockList = blockDao.listGroupBlock(userId,
				groupKeyids);

		List<WebBlock> specWebBlockList = blockDao.listBlockIds(userId,
				speckBlockids);
		webBlockList.addAll(specWebBlockList);

		// 准换内容的跳转URL
		convertBlockUrl(userId, templatePackageId, webBlockList, groupKeyInfos);

		final List<Integer> webBlockIdList = Lists.transform(webBlockList,
				new Function<WebBlock, Integer>() {
					@Override
					public Integer apply(WebBlock input) {
						return input.getId();
					}
				});

		// 获取模板所有的关联的网页块关联的参数
		Map<Integer, List<WebBlockVar>> blockVarMap = webBlockVarService
				.getBlockVars(webBlockIdList);

		Map<String, List<WebBlock>> groupMap = new HashMap<String, List<WebBlock>>();
		// 将内容按照分类KEY进行分類
		for (WebTemplateGroupkey webTemplateGroupkey : groupKeyInfos) {
			String groupKey = webTemplateGroupkey.getGroupKey();
			for (WebBlock webBlock : webBlockList) {
				if (!webBlock.getGroupKeyId().equals(
						webTemplateGroupkey.getId()))
					continue;
				List<WebBlock> blockList = groupMap.get(groupKey);
				if (blockList == null) {
					blockList = new ArrayList<WebBlock>();
					groupMap.put(groupKey, blockList);
				}
				blockList.add(webBlock);
			}
		}
		// 对分类KEY如果是设置了资源模板KEY的则重新再分类一次
		for (WebTemplateGroupkey webTemplateGroupkey : groupKeyInfos) {
			String resourceKey = webTemplateGroupkey.getResourceKey();
			if (StringUtils.isEmpty(resourceKey))
				continue;

			for (WebBlock webBlock : webBlockList) {
				if (!webBlock.getGroupKeyId().equals(
						webTemplateGroupkey.getId()))
					continue;
				List<WebBlock> blockList = groupMap.get(resourceKey);
				if (blockList == null) {
					blockList = new ArrayList<WebBlock>();
					groupMap.put(resourceKey, blockList);
				}
				blockList.add(webBlock);
			}
		}

		List<WebTemplateKeyResp> groupDtoList = new ArrayList<WebTemplateKeyResp>();
		for (String groupKey : groupMap.keySet()) {
			WebTemplateKeyResp webGroupDto = new WebTemplateKeyResp();
			List<WebBlock> blockList = groupMap.get(groupKey);
			List<WebBlockDto> blockDtoList = BeanCopy.copy(blockList,
					WebBlockDto.class);
			for (WebBlockDto webBlockDto : blockDtoList) {
				List<WebBlockVar> vars = blockVarMap.get(webBlockDto.getId());
				webBlockDto.blockVar2Map(vars);
			}
			webGroupDto.setGroupKey(groupKey);
			webGroupDto.setBlockList(blockDtoList);
			groupDtoList.add(webGroupDto);
		}

		return groupDtoList;
	}

	/**
	 * 转换路径
	 * 
	 * @param webBlock
	 */
	private void convertBlockUrl(Integer userId, Integer templatePackageId,
			List<WebBlock> webBlockList, List<WebTemplateGroupkey> groupKeyInfos) {

		List<WebTemplate> allTemplateList = templateDao
				.findByTemplatePackageId(userId, templatePackageId);
		Map<Integer, WebTemplate> templateMap = Maps.newHashMap();
		for (WebTemplate webTemplate : allTemplateList) {
			templateMap.put(webTemplate.getId(), webTemplate);
		}

		Map<Integer, WebTemplateGroupkey> groupKeyMap = Maps.newHashMap();
		for (WebTemplateGroupkey webTemplateGroupkey : groupKeyInfos) {
			groupKeyMap.put(webTemplateGroupkey.getId(), webTemplateGroupkey);
		}

		for (WebBlock webBlock : webBlockList) {
			WebTemplate webTemplate = templateMap.get(webBlock.getTemplateId());
			WebTemplateGroupkey webTemplateGroupkey = groupKeyMap.get(webBlock
					.getGroupKeyId());

			if (webTemplateGroupkey == null
					|| StringUtils.isEmpty(webTemplateGroupkey.getGroupKey()))
				continue;

			if (webTemplate == null
					|| StringUtils.isEmpty(webTemplate.getTemplatePath()))
				continue;

			if (webBlock.getLinkType() == null
					|| !webBlock.getLinkType().equals(
							BlockLinkType.RESOURCE.getValue())
					|| webBlock.getTemplateId() == null) {
				continue;
			}

			String linkUrl = webTemplate.getTemplatePath() + "?"
					+ groupKeyMap.get(webBlock.getGroupKeyId()).getGroupKey()
					+ "!bId=" + webBlock.getId();
			webBlock.setLinkUrl(linkUrl);

		}

	}

	/**
	 * 查询主题中所有使用了资源模板的内容消息的，对应获取资源模板需要的键值
	 * 
	 * @param userId
	 * @param templatePackageId
	 * @return
	 */
	public Map<String, List<WebTemplateKeyResp>> getAllResourceBlock(
			Integer userId, Integer templatePackageId) {
		Map<String, List<WebTemplateKeyResp>> blockResMap = Maps.newHashMap();
		List<WebTemplateGroupkey> groupList = groupKeyDao.findEffGroupKeys(
				userId, templatePackageId);
		final List<Integer> groupIdList = Lists.transform(groupList,
				new Function<WebTemplateGroupkey, Integer>() {
					@Override
					public Integer apply(WebTemplateGroupkey input) {
						return input.getId();
					}
				});
		// 查询多个配置资源模板的内容
		List<WebBlock> webBlockList = blockDao
				.listResBlock(userId, groupIdList);

		convertBlockUrl(userId, templatePackageId, webBlockList, groupList);

		for (WebBlock webBlock : webBlockList) {
			if (StringUtils.isEmpty(webBlock.getLinkUrl()))
				continue;
			int index = webBlock.getLinkUrl().indexOf("?");
			String linkUrl = webBlock.getLinkUrl();
			String templateName = webBlock.getLinkUrl().substring(0, index);
			String urlReqParam = webBlock.getLinkUrl().substring(index+1);
			List<WebTemplateKeyResp> keyList = listTemplateBlock(userId,
					templatePackageId, templateName, urlReqParam);
			blockResMap.put(linkUrl, keyList);
		}
		return blockResMap;
	}
}
